//
//  ImageCell.swift
//  物料商行
//
//  Created by HaoDong Hong on 2017/9/17.
//  Copyright © 2017年 HaoDong Hong. All rights reserved.
//

import UIKit

protocol ImageCellDelegate: class {
    func insert(image: CodablePictureOfMaterial)
    func deleteImage(at index: Int)
}

class ImageCell: UITableViewCell, UICollectionViewDelegate, UICollectionViewDataSource {
    
    @IBOutlet weak var collectionView: UICollectionView!
    @IBOutlet weak var addButton: UIButton!
    @IBOutlet weak var constraint: NSLayoutConstraint!
    var edited = true {
        didSet {
            if edited == false {
                constraint.constant = 8
            }
        }
    }
    
    var images = [Any]()
    weak var delegate: ImageCellDelegate?

    override func awakeFromNib() {
        super.awakeFromNib()
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.register(UINib(nibName: "ImageInsideCell", bundle: nil), forCellWithReuseIdentifier: "ImageInsideCell")

    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return images.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let row = indexPath.row
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ImageInsideCell", for: indexPath) as! ImageInsideCell
        if let image = images[row] as? UIImage {
            cell.imageView.image = image
        } else {
            if let url = URL(string: (images[row] as! String)) {
                cell.imageView.kf.setImage(with: url)
            }
        }
        cell.deleteButton.isHidden = !edited
        cell.deleteButton.addTarget(self, action: #selector(deleteBtTapped(_:)), for: .touchUpInside)
        return cell
    }
    func addImage() {
        // already insert image to images, so just update view
        let base64 = convertToBase64(images.last! as! UIImage)!
        delegate?.insert(image: CodablePictureOfMaterial(img: base64))
        let indexPath = IndexPath(row: images.count-1, section: 0)
        collectionView.performBatchUpdates({
            collectionView.insertItems(at: [indexPath])
        }, completion: nil)
    }
    @objc func deleteBtTapped(_ button: UIButton!) {
        let point = button.convert(CGPoint.zero, to: collectionView)
        guard let indexPath = collectionView.indexPathForItem(at: point) else {
            return
        }
        images.remove(at: indexPath.row)
        delegate?.deleteImage(at: indexPath.row)
        collectionView.performBatchUpdates({
            collectionView.deleteItems(at: [indexPath])
        }, completion: nil)
    }
}

